import AccessEnum from '@/access/accessEnum'
import { useLoginUserStore } from '@/stores/user'
import NProgress from '@/utils/nprogress'
import { createRouter, createWebHistory } from 'vue-router'
import routes from './routes'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: routes,
})

router.beforeEach(async (to, from, next) => {
  NProgress.start()
  const loginUserStore = useLoginUserStore()
  if (!loginUserStore.loginUser?.id) {
    await loginUserStore.fetchLoginUser()
  }
  const loginUser = loginUserStore.loginUser
  const isAdmin = loginUser?.userRole === AccessEnum.ADMIN
  if (isAdmin && to.path !== '/admin/data' && from.path === '/user/login') {
    next('/admin/data')
  } else {
    next()
  }
})

router.afterEach(() => {
  NProgress.done()
})

export default router
